// LoginController.java

package edu.cu.cs214.hw9.controller;


import javax.swing.JFrame;
import javax.swing.JOptionPane;

import edu.cmu.cs214.hw9.db.Constants;
/**
 * The controller for the Login window
 * @author davidzheng
 *
 */
public class LoginController extends AbstractController{

	public LoginController(JFrame window)
	{
		super(window);
	}
	/**
	 * Attempts to log the user in, given the email and password
	 * @param email the user's email
	 * @param password the user's password
	 * @return true on success
	 */
	public boolean login(String email, String password){
		//do checks that don't require a connection, so that we won't open it unless we have to
		if (!checkEmpty(email, password)) return false; //if either field is empty, return
		if (!checkValid(email)) return false; //if email is invalid, return false
		try{
			openConnection(Constants.SERVER_PORT0);
			//check that user exists in database
			
			//sends message with request to server
			out.println("EXISTS "+email);
			if(in.readLine().equals("false"))//server indicates user does not exist
			{
				JOptionPane.showMessageDialog(window, "No user with given e-mail exists",
						"Login Failure", JOptionPane.PLAIN_MESSAGE);
				out.println("END");
				closeConnection();
				return false;
			}
			//checks that password is correct
			out.println("PASSWORD "+email);
			String pass = in.readLine();
			if(pass == null) //this is unexpected, probably due to database
			{
				JOptionPane.showMessageDialog(window, "Database error: Try again",
						"Login Failure", JOptionPane.PLAIN_MESSAGE);
				out.println("END");
				closeConnection();
				return false;
			}
			if(!pass.equals(password))
			{
				JOptionPane.showMessageDialog(window, "Password is incorrect for given e-mail",
						"Login Failure", JOptionPane.PLAIN_MESSAGE);
				out.println("END");
				closeConnection();
				return false;
			}
			out.println("END");
			closeConnection();
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * Checks if email is valid.  Very basic, only checks for "@" and no ":",
	 * since ":" is a crucial message character for our messages.
	 * @param email the email
	 * @return whether it is valid
	 */
	private boolean checkValid(String email) {
		if (email.contains("@") && !email.contains(":")) return true;
		else 
		{
			JOptionPane.showMessageDialog(window, "Invalid Email",
					"Login Failure", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
	}
	/**
	 * checks to see if fields are blank
	 * @param email email
	 * @param password password
	 * @return true if empty
	 */
	private boolean checkEmpty(String email, String password) {
		if (!(email.isEmpty()||password.isEmpty()))
			return true;
		else
		{
			JOptionPane.showMessageDialog(window, "Empty inputs not allowed",
					"Login Failure", JOptionPane.PLAIN_MESSAGE);
			return false;
		}
	}
}